package com.meixiaoliang.portal.modular.system.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meixiaoliang.portal.core.util.AssertUtil;
import com.meixiaoliang.portal.core.util.EncryptUtil;
import com.meixiaoliang.portal.core.util.PageUtil;
import com.meixiaoliang.portal.core.util.ResponseUtil;
import com.meixiaoliang.portal.modular.system.model.User;
import com.meixiaoliang.portal.modular.system.model.UserRole;
import com.meixiaoliang.portal.modular.system.model.constant.Constant;
import com.meixiaoliang.portal.modular.system.model.enums.BooleanEnum;
import com.meixiaoliang.portal.modular.system.model.enums.DictionaryGroupEnum;
import com.meixiaoliang.portal.modular.system.model.searcher.UserSearcher;
import com.meixiaoliang.portal.modular.system.service.RoleService;
import com.meixiaoliang.portal.modular.system.service.UserRoleService;

/**
 *
 *
 * @author mei.xiaoliang@qq.com
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService     roleService;

    /** 密码加密的盐 */
    @Value("${password.salt}")
    public String           salt;

    /** 密码转换次数 */
    @Value("${password.transTime}")
    public int              transTime;

    /**
     * 用户分页-查询
     */
    //    @RequiresPermissions("system:user")
    @PostMapping("/list")
    public String list(UserSearcher searcher) {
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda().select(User::getId, User::getName, User::getRealName, User::getMobile,
            User::getStatus);
        if (StringUtils.isNotBlank(searcher.getName())) {
            queryWrapper.like(User::getRealName, searcher.getName());
        }
        IPage<User> iPage = userService.page(PageUtil.build(searcher), queryWrapper);
        List<User> list = iPage.getRecords();
        for (User user : list) {
            user.setStatusValue(dictionaryService.getDictValue(DictionaryGroupEnum.USER_STATUS, user.getStatus()));
            user.setRoles(roleService.getRolesByUserId(user.getId()));
            user.setStatusBool(user.getStatus() == BooleanEnum.TRUE.getCode());
        }
        return ResponseUtil.buildSuccessPageResponse(iPage);
    }

    /**
     * 校验用户名是否已存在, 返回 true 表示该账号已存在，不可使用
     */
    @RequestMapping("/checkName")
    public String checkName(String name, Integer id) {
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda().eq(User::getName, name);
        if (null != id && 0 != id) {
            queryWrapper.ne(User::getId, id);
        }
        List<User> userList = userService.list(queryWrapper);
        boolean result = false;
        if (userList.size() > 0) {
            result = true;
        }
        return ResponseUtil.buildSuccessResponse(result);
    }

    /**
     * 用户详情
     */
    @RequestMapping("/get")
    public String get(Integer id) {
        // 用户信息
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda().select(User::getId, User::getName, User::getRealName).eq(User::getId, id);
        User user = userService.getOne(queryWrapper);
        // 用户角色
        user.setRoleList(roleService.listIdByUserId(id));
        return ResponseUtil.buildSuccessResponse(user);
    }

    /**
     * 用户新增
     */
    @PostMapping("/save")
    public String save(User user) {
        // 用户新增
        user.setId(null);
        user.setStatus(BooleanEnum.TRUE.getCode());
        user.setPassword(EncryptUtil.transform(Constant.DEFAULT_PWD, salt, transTime));
        userService.save(user);
        // 用户-角色关系新增
        List<UserRole> userRoleList = new ArrayList<>();
        for (Integer roleId : user.getRoleList()) {
            userRoleList.add(new UserRole().setRoleId(roleId).setUserId(user.getId()).setDeleted(BooleanEnum.FALSE.getCode()));
        }
        userRoleService.saveBatch(userRoleList);
        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 用户修改
     */
    //    @RequiresPermissions("system:user")
    @PostMapping("/update")
    public String update(User user) {

        // 用户信息更新
        userService.updateById(user);

        // 用户角色更新
        userRoleService.remove(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, user.getId()));
        List<UserRole> userRoleList = new ArrayList<>();
        for (Integer roleId : user.getRoleList()) {
            userRoleList.add(new UserRole().setRoleId(roleId).setUserId(user.getId()).setDeleted(BooleanEnum.FALSE.getCode()));
        }
        userRoleService.saveBatch(userRoleList);

        return ResponseUtil.buildSuccessResponse();
    }

    //    @RequiresPermissions("system:user")
    @PostMapping("/delete")
    public String delete(int id) {
        // 删除用户
        userService.removeById(id);
        // 删除用户角色
        userRoleService.remove(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, id));
        return ResponseUtil.buildSuccessResponse();
    }

    @PostMapping("/unlock")
    public String unlock(Integer id) {
        User user = new User().setStatus(BooleanEnum.TRUE.getCode());
        user.setId(id);
        userService.updateById(user);
        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 用户冻结
     */
    @PostMapping("/lock")
    public String lock(Integer id) {
        User user = new User().setStatus(BooleanEnum.FALSE.getCode());
        user.setId(id);
        userService.updateById(user);
        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 修改密码
     */
    @RequestMapping("/updatePwd")
    public String updatePwd(Integer id, String password) {
        User user = new User().setId(id).setPassword(EncryptUtil.transform(password, salt, transTime));
        userService.updateById(user);
        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 修改自己密码
     */
    @PostMapping("/updateSelfPwd")
    public String updateSelfPwd(String oldPassword, String newPassword) {
        // 修改密码时后台再校验，双保险，但是没什么卵用。
        AssertUtil.isTrue(checkSelfPassword(getCurrentUserId(), oldPassword), "旧密码错误");
        // 主要逻辑
        User user = new User().setPassword(EncryptUtil.transform(newPassword, salt, transTime));
        user.setId(getCurrentUserId());
        userService.updateById(user);
        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 检查自身密码是否正确，修改密码时使用
     */
    @RequestMapping("/checkSelfPwd")
    public String checkSelfPwd(String password) {
        return ResponseUtil.buildSuccessResponse(checkSelfPassword(getCurrentUserId(), password));
    }

    private boolean checkSelfPassword(Integer userId, String password) {
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda().eq(User::getId, userId);
        User item = userService.getOne(queryWrapper);
        boolean result = false;
        if (StringUtils.equals(item.getPassword(), EncryptUtil.transform(password, salt, transTime))) {
            result = true;
        }
        return result;
    }

    @PostMapping("/resetPwd")
    public String resetPwd(Integer userId) {
        String transPwd = EncryptUtil.transform(Constant.DEFAULT_PWD, salt, transTime);
        logger.info("resetPwd trans: {}", transPwd);
        User user = new User().setPassword(transPwd);
        user.setId(userId);
        userService.updateById(user);
        return ResponseUtil.buildSuccessResponse();
    }

}
